package com.example.uploadresultliga.callapi;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.AsyncTask;

import com.example.uploadresultliga.to.Categoria;
import com.example.uploadresultliga.to.ConfigTorneo;
import com.example.uploadresultliga.to.Fecha;
import com.example.uploadresultliga.util.ServicesParams;

public class CallConfigTorneoAPI extends AsyncTask<String, String, ConfigTorneo> {

	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[] DUMMY_CREDENTIALS = new String[] {"foo@example.com:hello", "bar@example.com:world", "dromero@agea.com.ar:1212javc" };

	@Override
    protected ConfigTorneo doInBackground(String... params) {
		boolean loginOK = false;
		String mEmail = params[0];
		String mPassword = params[1];
		for (String credential : DUMMY_CREDENTIALS) {
			String[] pieces = credential.split(":");
			if (pieces[0].equals(mEmail) && pieces[1].equals(mPassword)) {
				// Account exists, return true if the password matches.
				loginOK = true;
				break;
			}
		}
		if(!loginOK) {
			return null;
		}

		ConfigTorneo configTorneo = null;
    	StringBuilder resultToDisplay = new StringBuilder();
        try {
        	byte[] buffer = new byte[1024];
	        InputStream in = null;
            URL url = new URL(ServicesParams.CONFIG_TORNEO_SERVICE);

            System.err.println("llamando al servicio " + ServicesParams.CONFIG_TORNEO_SERVICE + " ...");

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream());
            int i = in.read(buffer, 0, buffer.length);
            while(i!=-1) {
            	resultToDisplay.append(new String(buffer, "UTF-8"));
            	i = in.read(buffer, 0, i);
            }
            in.close();
            JSONObject jsonObj = new JSONObject(resultToDisplay.toString());
            System.err.println("RECIBI ESTO -> " + resultToDisplay.toString().trim());
            configTorneo = new ConfigTorneo(jsonObj.getString("nombreTorneo"), jsonObj.getString("zona"), jsonObj.getInt("rondaActual"));
            JSONArray jsonArrayFechas = jsonObj.getJSONArray("fechas");
            for(int ii=0; ii<jsonArrayFechas.length(); ii++) {
            	JSONObject jsonFecha = jsonArrayFechas.getJSONObject(ii);
            	configTorneo.getFechas().add(new Fecha(jsonFecha.getInt("id"), (String)jsonFecha.get("nombre"), (String)jsonFecha.get("desde")));
            }
            JSONArray jsonArrayCat = jsonObj.getJSONArray("categorias");
            for(int ii=0; ii<jsonArrayCat.length(); ii++) {
            	JSONObject jsonCat = jsonArrayCat.getJSONObject(ii);
            	configTorneo.getCategorias().add(new Categoria(jsonCat.getInt("id"), jsonCat.getInt("anio")));
            }
         } catch (Exception e) {
        	 e.printStackTrace();
         }
        return configTorneo;
    }

} // end
